<template>
  <div>
    <NormalForm pageTitle="漏斗分析" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt" @handleQuery="handleQuery" @handleReset="handleReset" @selectDateType="selectDateType"></NormalForm>
    <div v-loading="loading">
      <div class="main wrap g-card">
        <div class="title-header">客户旅程<svg-icon icon-class="question-white" /></div>
        <div class="mainTable">
          <div class="tableItem picInfo">
            <div class="pic">
              <p v-for="(item, index) in tableData" :key="index">
                {{ item.tableState }}:{{ item.conversionRate }}</p>
            </div>
            <div class="info">
              <p v-for="(item, index) in tableData" :key="index">
                {{ item.count }}人</p>
            </div>
          </div>
          <div class="tableItem">
            <div class="table-info">
              <div class="item mr20">
                <p>成交客户</p>
                <p>{{ dealCus }}<span>人</span></p>
                <p>较昨日：
                  <img :src="require(`../../../../assets/cutomer/${dealCusFlag ? 'down' : 'jump'}.png`)" alt="">
                  <span>{{ dealCusRate }}%</span>
                </p>
              </div>
              <div class="item">
                <p>成交转化率</p>
                <p>{{ conversionRate }}</p>
                <p>较昨日：
                  <img :src="require(`../../../../assets/cutomer/${converRateFlag ? 'down' : 'jump'}.png`)" alt="">
                  <span>{{ converRate }}%</span>
                </p>
              </div>
            </div>
            <el-table :data="tableData">
              <el-table-column prop="tableState" label="阶段" align="center">
              </el-table-column>
              <el-table-column prop="count" label="人数" align="center">
              </el-table-column>
              <el-table-column prop="conversionRate" label="阶段转化率" align="center">
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="wrap g-card">
        <div class="title-header">成交转化率趋势(%)</div>
        <div class="chartBox">
          <div class="chartItem" id="chartOne"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAllWeUser } from "@/api/customer/customerManage"
import * as echarts from "echarts";
import "echarts-wordcloud";
import { parseTime } from "@/utils/common"
import { getQueryJourney } from '@/api/customerInsight/analysis'

export default {
  data() {
    return {
      queryForm: {
        dateType: '0',
        dateRange: null,
        deptId: null,
        createCode: null,
        insuranceType: null,
      },
      formList: [
        {
          label: '渠道',
          value: '',
          prop: 'insuranceType',
          type: 'SELECT',
          emunName: 'insuranceList',
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createCode',
          type: 'SELECT',
          emunName: 'creatorList'
        },
        {
          label: '',
          value: '',
          prop: 'dateType',
          type: 'SPECIAL_SELECT',
          emunName: 'dateTypeList'
        },
        {
          label: '',
          value: null,
          prop: 'dateRange',
          type: 'SPECIAL_DATE',
          emunName: '',
          aboutProp: 'dateType',
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
          },
        },
      ],
      enumOpt: {
        insuranceList: [],
        creatorList: [],
        dateTypeList: [
          { dictLabel: '自然日', dictValue: '0' },
          { dictLabel: '自然周', dictValue: '1' },
          { dictLabel: '自然月', dictValue: '2' },
          { dictLabel: '自然年', dictValue: '3' },
        ],
      },
      dealCus: 0,//成交客户
      dealCusRate: 0,//成交客户较昨日
      conversionRate: 0,//成交客户转化率
      converRate: 0,//成交客户转化率较昨日
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();;
        },
      },
      loading: false,
      message: {},//返参
      tableData: [
        {
          tableState: '获取',
          count: '0',
          conversionRate: '0.00%',
          followState: 0,
        },
        {
          tableState: '初步意向',
          count: '0',
          conversionRate: '0.00%',
          followState: 1,
        },
        {
          tableState: '意向',
          count: '0',
          conversionRate: '0.00%',
          followState: 2,
        },
        {
          tableState: '成交',
          count: '0',
          conversionRate: '0.00%',
          followState: 4,
        },
        {
          tableState: '复购',
          count: '0',
          conversionRate: '0.00%',
        },
      ]
    }
  },
  computed: {
    dealCusFlag() {
      this.dealCusRate = String(this.dealCusRate).replaceAll('%', "");
      return this.dealCusRate < 0
    },
    converRateFlag() {
      this.converRate = String(this.converRate).replaceAll('%', "");
      return this.converRate < 0
    },
  },
  watch: {
    "queryForm.deptId": {
      handler() {
        if(this.queryForm.deptId) this.getAllWeUserInfo();
      },
    },
  },
  created() {
    this.getLabelList();
    this.selectDateType();
    this.handleQuery();
  },
  methods: {
    getLabelList() {
      // 渠道
      this.getDicts("insurance_type").then((res) => {
        if (res.code === 200) {
          this.enumOpt.insuranceList = res.data
        }
      });
    },
    getAllWeUserInfo() {
      this.enumOpt.creatorList = []
      const params = {
        deptId: this.queryForm.deptId,
        userName: "",
      };
      getAllWeUser(params).then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.enumOpt.creatorList.push({
              dictLabel: item.userName,
              dictValue: item.userId
            })
          })
        }
      })
    },
    selectDateType() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), "{y}-{m}-{d}");
      let endTime = parseTime(new Date(new Date().getTime()), "{y}-{m}-{d}");
      if (this.queryForm.dateType === "0") {
        this.queryForm.dateRange = [startTime, endTime];
      } else {
        this.queryForm.dateRange = startTime
      }
    },
    handleQuery() {
      // let obj = this.reassembly();
      // const params = {
      //   dateType: obj.dateType,
      //   startDate: obj.startTime,
      //   endDate: obj.endTime,
      //   deptId: this.queryForm.deptId,
      //   createCode: this.queryForm.createCode,
      //   insuranceType: this.queryForm.insuranceType,
      // };
      // this.loading = true;
      // getQueryJourney(params).then((res) => {
      //   if (res.code === 200) {
      //     this.message = res.data || {};
      //     this.tableData.some((item) => {
      //       if (item.tableState === '复购') {
      //         item.count = this.message.funnelResVO.repurchase;
      //         item.conversionRate = this.message.funnelResVO.repurchaseConversionRate;
      //       } else if (item.tableState === '获取') {
      //         item.count = this.message.funnelResVO.obtain;
      //         item.conversionRate = '100%';
      //       } else if (item.tableState === '初步意向') {
      //         item.count = this.message.funnelResVO.preliminaryIntention;
      //         item.conversionRate = this.message.funnelResVO.preliminaryIntentionConversionRate;
      //       } else if (item.tableState === '意向') {
      //         item.count = this.message.funnelResVO.intention;
      //         item.conversionRate = this.message.funnelResVO.intentionConversionRate;
      //       } else if (item.tableState === '成交') {
      //         item.count = this.message.funnelResVO.deal;
      //         item.conversionRate = this.message.funnelResVO.dealConversionRate;
      //       }
      //     })
      //     this.dealCus = this.message.funnelResVO.deal || 0;
      //     this.conversionRate = this.message.funnelResVO.dealConversionRate || 0;
      //     this.dealCusRate = this.message.dealComparedWithYesterday || 0;
      //     this.converRate = this.message.dealConversionRateComparedWithYesterday || 0;
      //     this.getChartOne();
      //   }
      //   this.loading = false;
      // }).catch(() => {
      //   this.loading = false;
      //   console.log('error');
      // })
      this.message = {
        "funnelResVO": {
          "obtain": 153,
          "obtainConversionRate": "96.22%",
          "preliminaryIntention": 29,
          "preliminaryIntentionConversionRate": "18.23%",
          "intention": 9,
          "intentionConversionRate": "5.66%",
          "deal": 8,
          "dealConversionRate": "5.03%",
          "repurchase": 2,
          "repurchaseConversionRate": "1.26%"
        },
        "dealComparedWithYesterday": "50%",
        "dealConversionRateComparedWithYesterday": "50%",
        "transactionConversionRateList": [
          {
            "theDate": "2024-04-29",
            "transactionConversionRate": "0.00%"
          },
          {
            "theDate": "2024-04-22",
            "transactionConversionRate": "0.00%"
          },
          {
            "theDate": "2024-04-23",
            "transactionConversionRate": "0.00%"
          },
          {
            "theDate": "2024-04-24",
            "transactionConversionRate": "1%"
          },
          {
            "theDate": "2024-04-25",
            "transactionConversionRate": "1%"
          },
          {
            "theDate": "2024-04-26",
            "transactionConversionRate": "2%"
          },
          {
            "theDate": "2024-04-27",
            "transactionConversionRate": "2%"
          },
          {
            "theDate": "2024-04-28",
            "transactionConversionRate": "3%"
          }
        ]
      }
      this.tableData.some((item) => {
        if (item.tableState === '复购') {
          item.count = this.message.funnelResVO.repurchase;
          item.conversionRate = this.message.funnelResVO.repurchaseConversionRate;
        } else if (item.tableState === '获取') {
          item.count = this.message.funnelResVO.obtain;
          item.conversionRate = '100%';
        } else if (item.tableState === '初步意向') {
          item.count = this.message.funnelResVO.preliminaryIntention;
          item.conversionRate = this.message.funnelResVO.preliminaryIntentionConversionRate;
        } else if (item.tableState === '意向') {
          item.count = this.message.funnelResVO.intention;
          item.conversionRate = this.message.funnelResVO.intentionConversionRate;
        } else if (item.tableState === '成交') {
          item.count = this.message.funnelResVO.deal;
          item.conversionRate = this.message.funnelResVO.dealConversionRate;
        }
      })
      this.dealCus = this.message.funnelResVO.deal || 0;
      this.conversionRate = this.message.funnelResVO.dealConversionRate || 0;
      this.dealCusRate = this.message.dealComparedWithYesterday || 0;
      this.converRate = this.message.dealConversionRateComparedWithYesterday || 0;
      window.setTimeout(() => {
        this.getChartOne();
      },1000)
    },
    handleReset() {
      let startTime = parseTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), "{y}-{m}-{d}");
      let endTime = parseTime(new Date(new Date().getTime()), "{y}-{m}-{d}");
      this.enumOpt.creatorList = []
      this.queryForm = {
        dateType: '0',
        dateRange: [startTime, endTime],
        deptId: null,
        createCode: null,
        insuranceType: null,
      };
      this.handleQuery();
    },
    // 组装startTime和endTime入参
    reassembly() {
      let startTime = null, endTime = null, dateType = null;
      let selectDate = this.queryForm.dateRange;
      if (selectDate) {
        if (this.queryForm.dateType === "0") {
          dateType = 'DAY'; // 日
          startTime = selectDate[0]
          endTime = selectDate[1]
        } else if (this.queryForm.dateType === "1") {
          dateType = 'DAY'; // 周
          startTime = parseTime(new Date(new Date(selectDate).getTime() - 24 * 60 * 60 * 1000), "{y}-{m}-{d}")
          endTime = parseTime(new Date(new Date(selectDate).getTime() + 5 * 24 * 60 * 60 * 1000), "{y}-{m}-{d}")
        } else if (this.queryForm.dateType === "2") {
          dateType = 'MONTH'; // 月
          startTime = selectDate
          const temp = selectDate.split("-")
          let str = +temp[1] + 1
          temp[1] = temp[1] < 9 ?  '0' + str : str;
          if (temp[1] === 13) {
            temp[1] = "01"
            temp[0] = +temp[0] + 1
          }
          endTime = temp.join("-")
        } else if (this.queryForm.dateType === "3") {
          dateType = 'YEAR'; // 年
          startTime = selectDate
          const temp = selectDate.split("-")
          temp[0] = +temp[0] + 1
          endTime = temp.join("-")
        }
      }
      return { startTime, endTime, dateType }
    },
    //图表
    getChartOne() {
      let NameData = this.message.transactionConversionRateList.map(item => item.theDate) || [];
      let ConversionRate = this.message.transactionConversionRateList.map(item => {
        return item.transactionConversionRate.replace('%', '')
      }) || [];
      let mycharts = echarts.init(document.getElementById("chartOne"));
      let option = {
        tooltip: {
          trigger: "axis",
          formatter: "{b}<br/>{a}：{c}%",
        },
        legend: {
          //   orient: "vertical",
          x: "right", //可设定图例在左、右、居中
          y: "top", //可设定图例在上、下、居中
          padding: [30, 15, 0, 0], //可设定图例[距上方距离，距右方距离，距下方距离，距左方距离
          data: ["签单客户数量"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        color: ["#FFB860", "#082aff"],
        xAxis: {
          type: "category",
          data: NameData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "签单客户数量",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 5,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 2,
              },
            },
            showSymbol: true,
            areaStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    {
                      offset: 0,
                      color: "rgba(255,82,82,0.06)",
                    },
                    {
                      offset: 0.8,
                      color: "rgba(254,97,89,0)",
                    },
                  ],
                  false
                ),
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10,
              },
            },
            itemStyle: {
              normal: {
                color: "#082aff ",
                borderColor: "rgba(255,207,118,0.27)",
                borderWidth: 12,
              },
            },
            stack: "Total",
            data: ConversionRate,
          },
        ],
      };
      mycharts.setOption(option);
    },
  },
}
</script>
<style lang="scss" scoped>
@import "@/styles/element-ui.scss";
@import "@/styles/base.scss";

.wrap {
  margin-top: 20px;
  @include titleWrap;
  .title-header {
    border-bottom: none;
    margin-bottom: 0;
  }
}

.mainTable {
  width: 100%;
  display: flex;

  .tableItem {
    flex: 1;
    padding: 0 16px;

    .table-info {
      display: flex;

      .item {
        flex: 1;
        padding: 20px 28px;
        border: 1px solid #EEEEEE;
      }
    }

    .el-table {
      margin-top: 20px;
    }

    .pic {
      width: 70%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-image: url(../../../../assets/image/funnel.png);
      background-size: auto 100%;
      background-position: center 0;
      background-repeat: no-repeat;

      p {
        flex: 1;
        display: flex;
        align-items: center;
        color: #fff;
        margin-top: 20px;
      }

      p:nth-of-type(2) {
        margin-top: 45px;
      }

      p:nth-of-type(5) {
        color: #082aff;
      }
    }

    .info {
      width: 30%;
      display: flex;
      flex-direction: column;
      align-items: center;

      p {
        flex: 1;
        display: flex;
        align-items: center;
      }
    }
  }

  .picInfo {
    display: flex;
  }
}

.chartBox {
  width: 100%;
  height: 400px;
  display: flex;

  .chartItem {
    flex: 1;
    // border: 1px solid #eeeeee;
    // margin-right: 20px;
    box-sizing: border-box;
  }

  #chartOne {
    padding: 0 30px;
  }
}
</style>
